package com.collect.cameroon.zhiUtils.zhiVersion;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.collect.cameroon.MyApplication;
import com.collect.cameroon.zhiBean.zhiReceive.ZHIRAppVersionEntity;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.cameroon.zhiGlobal.zhiAppSettings.ZHIProjectRouter;
import com.collect.cameroon.zhiUtils.StringUtil;

import java.io.File;

public class ZHIVersionIMPL {

    public static String productLogo;
    public static String productName;
    public static String productLink;
    public static String productApkLocalPath;

    public static ZHIVersionIMPL getInstance() {
        return instance;
    }

    private static ZHIVersionIMPL instance = new ZHIVersionIMPL();

    public static void openProduct(ZHIVersion stupidVersion) {
        try {
            String productName = StringUtil.safeString(stupidVersion.getName());
            String productUrl = StringUtil.safeString(stupidVersion.getLink());
            String productLogo = StringUtil.safeString(stupidVersion.getLogo());

            ZHIVersionIMPL.productLink = productUrl;
            ZHIVersionIMPL.productLogo = productLogo;
            ZHIVersionIMPL.productName = productName;

            if (!openOnInstallApk(productUrl)) {
                if (!openOnGooglePlayStore(productUrl)) {
                    openOnBrowser(productUrl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean openOnInstallApk(String url) {
        try {
            if (TextUtils.isEmpty(url)) {
                Log.e(ZHIVersionIMPL.class.getSimpleName(), "openOnInstallApk: URL not found");
                return false;
            }
            if (isInstallApkUrl(url)) {
                //下载文件
                ZHIProjectRouter.toAppUpdate();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @SuppressLint("NewApi")
    public static boolean openOnGooglePlayStore(String url) {
        if (TextUtils.isEmpty(url)) {
            Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket: URL not found");
            return false;
        }
        if (isGooglePlayUrl(url)) {
            try {
                final String GOOGLE_PLAY = "com.android.vending";
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                intent.setPackage(GOOGLE_PLAY);
                if (intent.resolveActivity(MyApplication.getAppContext().getPackageManager()) != null) {
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    MyApplication.getAppContext().startActivity(intent);
                    return true;
                } else {
                    Intent intent2 = new Intent(Intent.ACTION_VIEW);
                    intent2.setData(Uri.parse(url));
                    if (intent2.resolveActivity(MyApplication.getAppContext().getPackageManager()) != null) {
                        intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        MyApplication.getAppContext().startActivity(intent2);
                        return true;
                    } else {
                        Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket Intent not found");
                        return false;
                    }
                }
            } catch (ActivityNotFoundException activityNotFoundException1) {
                activityNotFoundException1.printStackTrace();
                Log.e(ZHIVersionIMPL.class.getSimpleName(), "GoogleMarket Intent not found");
                return false;
            }
        }
        return false;
    }

    public static void openOnBrowser(String url) {
        try {
            if (TextUtils.isEmpty(url)) {
                Log.e(ZHIVersionIMPL.class.getSimpleName(), "openOnBrowser: URL not found");
                return;
            }
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (intent.resolveActivity(MyApplication.getAppContext().getPackageManager()) != null) {
                MyApplication.getAppContext().startActivity(intent);
            } else {
                MyApplication.getAppContext().startActivity(Intent.createChooser(intent, "Please select a browser to open"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean isInstallApkUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        if (StringUtil.safeString(url).toLowerCase().endsWith(ZHIProjectConfigs.INSTALL_APK_URL_SUFIX)) {
            return true;
        }

        String suffix = url.substring(url.lastIndexOf("."));
        return suffix.contains("apk");
    }

    public static boolean isGooglePlayUrl(String url) {
        return StringUtil.safeString(url).toLowerCase().startsWith(ZHIProjectConfigs.GOOGLE_PLAY_URL_PREFIX);
    }

    public static String getDownloadDir() {
        String path = null;
        String apkSaveDir = "getapk";
        try {
            File dataDir = MyApplication.getAppContext().getFilesDir();
            path = dataDir.getAbsolutePath() + File.separator + apkSaveDir;

            File gTargetDir = new File(path);
            if (!gTargetDir.exists()) {
                gTargetDir.mkdirs();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return path;
    }

    public static String getApkDownFinishPath() {
        String dir = getDownloadDir() + File.separator;
        String apkPath = dir + "gettempinstallfile_" + ZHIProjectConfigs.APP_VERSION + ".apk";
        return apkPath;
    }

    public static String getApkSavePath() {
        String dir = getDownloadDir() + File.separator;
        String apkPath = dir + "gettempinstallfile_" + ZHIProjectConfigs.APP_VERSION + ".apk";
        productApkLocalPath = apkPath;
        try {
            File oldFile = new File(apkPath);
            if (oldFile.exists()) {
                oldFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return apkPath;
    }

    public static boolean startInstallApk(String productApkLocalPath) {
        return ZHIInstallAPK.installApk(productApkLocalPath);
    }

    public static boolean handlerAppVersion(Context context, ZHIRAppVersionEntity zhirAppVersionEntity) {
        if (TextUtils.isEmpty(zhirAppVersionEntity.getLinkUrl())) {
            return false;
        }

        try {
            ZHIVersionIMPL.productLink = StringUtil.safeString(zhirAppVersionEntity.getLinkUrl());

            int oriInt = Integer.parseInt(ZHIProjectConfigs.APP_VERSION);
            //两手准备
//            String gVersion = zhirAppVersionEntity.getVersion();
//            if (TextUtils.isEmpty(gVersion)) {
//                gVersion = "0";
//            }
//
//            int gInt = Integer.parseInt(gVersion);
//            if (gInt > oriInt) {
//                ApkInfo apkInfo = new ApkInfo(9999, context.getResources().getString(R.string.app_name), zhirAppVersionEntity.getLinkUrl());
//                new ApkDownloader(context, apkInfo).downloadApk();
//                return true;
//            }

            String gpVersion = zhirAppVersionEntity.getGpVersion();
            if (TextUtils.isEmpty(gpVersion)) {
                gpVersion = "0";
            }

            int gpInt = Integer.parseInt(gpVersion);
            if (gpInt > oriInt) {
                ZHIProjectRouter.toAppUpdate();
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
